<template>
  <div class="ui-panle" style="position:relative">
    <code-editer  @codeEditorInit="codeEditorInit" @saveFileChange="getFileList(filepathStr)"></code-editer>
    <div class="file-path">
      <div id="file-breadcrumb" style="flex:1">
        <Select v-model="serverListSelect" :datas="serverListData" type="Object" @change="serverListChange" :no-border="true" :equal-width="false" :null-option="false" placeholder="选择服务器">
          <template slot-scope="{item}" slot="item">
            <div class="primary-color" style="padding:5px 0;"><b>{{item.title}}</b><span style="float:right;width:220px;text-align:right" class='gray1-color text-ellipsis'>{{item.hostname}}</span>
            </div>
            <div class='gray1-color' style="border-top:dashed 1px rgba(0,0,0,0.1)">{{item.guid}}</div>
          </template>
        </Select>
        <div id="file-breadcrumb-item" @click="filepath=[]">
          <span><i :class="isFileLoading?'h-icon-loading':'fas fa-desktop'"></i></span>
          <!-- &nbsp;&nbsp;<i class="el-icon-arrow-right"></i> -->
        </div>
        <div id="file-breadcrumb-item" v-for="(item,index) in filepath" :key="index" @click="changePath(index)" :title="filepath.slice(0,index+1).join('/') || '/'">
          <span>{{item}}</span>
          <!-- &nbsp;&nbsp;<i class="el-icon-arrow-right"></i> -->
        </div>
        <div id="file-breadcrumb-item" @click="getFileList(filepathStr)" v-if="serverListSelect!=null">
          <span><i class="fas fa-redo"></i>&nbsp;&nbsp;刷新</span>
          <!-- &nbsp;&nbsp;<i class="el-icon-arrow-right"></i> -->
        </div>
        <div id="file-breadcrumb-item">
          <span>&nbsp;</span>
          <!-- &nbsp;&nbsp;<i class="el-icon-arrow-right"></i> -->
        </div>
      </div>
      <SwitchList v-model="fileManageMode" :datas="[{key:'list',title:'',icon:'fas fa-th-list'},{key:'icon',title:'',icon:'fas fa-th'}]"></SwitchList>
      <!-- <el-radio-group v-model="fileManageMode" style="align-self:flex-end">
        <el-radio-button label="icon" title="图标模式"><i class="el-icon-s-grid" style="font-size:20px"></i></el-radio-button>
        <el-radio-button label="list" title="详细列表模式"><i class="el-icon-s-unfold" style="font-size:20px"></i></el-radio-button>
      </el-radio-group> -->
    </div>
    <!-- <div style="background:rgba(47,218,178);padding:10px;display:inline-block;border-radius:100px;color:#fff">
      <i class="el-icon-refresh-right"></i>
    </div> -->
    <div class="file-panle">
      <div class="file-icon-box" v-if="fileManageMode=='icon'">
        <div id="item" class="text-ellipsis" v-for="(item,index) in sortFileData" :key="index" :title="item.name">
          <div class="list-file" v-if="item.isFile" @click="readfile(item)">
            <i class="fas fa-file-alt"></i>
            <span class="text-ellipsis">{{item.name}}</span>
            <div id="size">{{toSize(item.size)}}</div>
          </div>
          <div class="list-dir" v-else @click="filepath.push(item.path)">
            <i class="fas fa-folder"></i>
            <span class="text-ellipsis">{{item.name}}</span>
          </div>
        </div>
        <Loading text="Loading" :loading="isFileLoading"></Loading>
        <!-- <el-empty v-if="sortFileData.length==0" description="此文件夹为空"></el-empty> -->
      </div>
      <div class="file-list-box" v-else>
        <Table :datas="sortFileData" :checkbox="true" ref="filetable" @select="fileTableSelect" :loading="isFileLoading">
          <TableItem title="文件名">
            <template slot-scope="{data}">
              <div id="file" v-if="data.isFile" @click="fileTabledblclick(data)">
                <i class="fas fa-file-alt"></i>
                &nbsp;&nbsp;<span class="text-ellipsis">{{data.name}}</span>
              </div>
              <div id="file" v-else @click="fileTabledblclick(data)">
                <i class="fas fa-folder" style="color:#2fdab2"></i>&nbsp;&nbsp;
                <span class="text-ellipsis">{{data.name}}</span>
              </div>
            </template>
          </TableItem>
          <TableItem title="文件大小" align="center">
            <template slot-scope="{data}">
              {{toSize(data.size)}}
            </template>
          </TableItem>
          <TableItem title="最后修改时间" align="center">
            <template slot-scope="{data}">
              {{new Date(data.time).format('yyyy/MM/dd hh:mm:ss')}}
            </template>
          </TableItem>
          <TableItem title="操作" align="center">
            <template slot-scope="{data}">
              <button class="h-btn h-btn-s h-btn-primary" style="height:30px;" :disabled="!data.isFile" @click="readfile(data)"><i class="fas fa-edit"></i></button>&nbsp;&nbsp;
              <!-- <button class="h-btn h-btn-s h-btn-red" @click="removefile(data)"><i class="h-icon-trash"></i></button> -->
              <Poptip content="确认永久删除？" @confirm="removeOneFiles(data.path)">
                <button style="height:30px;" class="h-btn h-btn-s h-btn-red"><i class="h-icon-trash"></i></button>
              </Poptip>
            </template>
          </TableItem>
          <div slot="empty">此文件夹为空</div>
        </Table>
        <!-- <el-table :data="sortFileData" style="width: 100%" @row-dblclick="fileTabledblclick" empty-text="此文件夹为空">
          <el-table-column label="文件名">
            <template slot-scope="scope">
              <div v-if="scope.row.isFile">
                <i class="el-icon-document"></i>
                &nbsp;&nbsp;<span class="text-ellipsis">{{scope.row.name}}</span>
              </div>
              <div v-else>
                <i class="el-icon-folder" style="color:#2fdab2"></i>&nbsp;&nbsp;
                <span class="text-ellipsis">{{scope.row.name}}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="文件大小" align="center">
            <template slot-scope="scope">
              {{toSize(scope.row.size)}}
            </template>
          </el-table-column>
          <el-table-column prop="time" label="最后修改时间" align="center">
            <template slot-scope="scope">
              {{new Date(scope.row.time).format('yyyy-MM-dd hh:mm:ss')}}
            </template>
          </el-table-column>
        </el-table> -->
        <div class="file-toolbar">
          <div class="item" style="font-size:12px">
            {{fileData.length}} 个项目
            <!-- <DropdownCustom button>
              <span>新 建</span>
              <div slot="content">
                <div class="dropdown-item"><i class="fas fa-folder" style="color:#2fdab2"></i>&nbsp;&nbsp;新建文件夹</div>
              </div>
            </DropdownCustom> -->
          </div>
          <div class="item" id="remove" v-if="selectTableData.length>0">
            <Poptip content="确认永久删除？" @confirm="removeFiles">
              <button style="height:30px;" class="h-btn h-btn-s h-btn-red"><i class="h-icon-trash"></i> 批量删除</button>
            </Poptip>
          </div>
        </div>
      </div>
    </div>
    <Loading text="Loading" :loading="readfileLoading"></Loading>
  </div>
</template>

<script>
export default {
  data() {
    return {
      readfileLoading: false,
      serverListSelect: null,
      serverListData: [],
      fileManageMode: 'list',
      editor: null,
      filepath: [],
      fileData: [],
      isFileLoading: false,
      selectTableData: []
    }
  },
  watch: {
    filepathStr(val) {
      this.getFileList(val)
    }
  },
  computed: {
    filepathStr() {
      return ('/' + this.filepath.join('/') + '/').replace(/\/+/g, '/')
    },
    sortFileData() {
      let s = this.fileData
      s.sort((a, b) => {
        if (a.isFile == b.isFile) {
          return a.name.toLowerCase().charCodeAt(0) - b.name.toLowerCase().charCodeAt(0)
        }
        return a.isFile - b.isFile
      })
      return this.fileData
    }
  },
  mounted: function () {
    this.getServerList()
    // this.getFileList(this.filepathStr)
  },
  methods: {
    serverListChange(data) {
      //console.log(data)
      this.$file.setPort(data.key)
      this.getFileList('')
    },
    async removeOneFiles(data) {
      this.isFileLoading = true
      let ret = await this.$file.delfile(this.filepathStr, [data])
      if (ret.code < 0) {
        this.$Notice({
          type: 'error',
          title: '错误',
          content: ret.msg
        });
        this.isFileLoading = false
        return
      } else {
        this.$Notice({
          type: 'success',
          title: '成功',
          content: ret.msg
        });
        this.getFileList(this.filepathStr)
      }
      this.isFileLoading = false
    },
    async removeFiles() {
      this.isFileLoading = true
      let ret = await this.$file.delfile(this.filepathStr, this.selectTableData)
      if (ret.code < 0) {
        this.$Notice({
          type: 'error',
          title: '错误',
          content: ret.msg
        });
        this.isFileLoading = false
        return
      } else {
        this.$Notice({
          type: 'success',
          title: '成功',
          content: ret.msg
        });
        this.getFileList(this.filepathStr)
      }
      this.isFileLoading = false
    },
    fileTableSelect(e) {
      //console.log(e)
      this.selectTableData = e.map((item) => {
        return item.path
      })
    },
    codeEditorInit(editor) {
      //   console.log('编辑器初始化完成')
      this.editor = editor
    },
    async getServerList() {
      let ret = await this.$API.getserver()
      this.serverListData = ret.map((item, index) => {
        return {
          title: '#' + (index + 1),
          hostname: item.configinfo.server_hostname,
          key: parseInt(item.server_port),
          guid: item.server_guid,
          rcon: {
            port: item.configinfo.rcon_port,
            password: item.configinfo.rcon_password
          }
        }
      })
    },
    fileTabledblclick(data, event, index) {
      if (data.isFile) {
        // this.readfile(data)
      }
      else {
        this.filepath.push(data.path)
      }
    },
    toSize(size) {
      size = Number(size)
      let unit = ['B', 'KB', 'MB', 'GB']
      for (let i = 0, step = 1; i < unit.length; i++) {
        //console.log(size / step, size, step, unit[i], i)
        if (size / step < step) {
          return (size / step).toFixed(2) + ' ' + unit[i]
        }
        step *= 1024
      }
    },
    async readfile(item) {
      if (item.isFile) {
        this.readfileLoading = true
        this.editor.openFile(this.filepathStr + item.path,this.serverListSelect).then(isLoading => {
          this.readfileLoading = false
        })
      }


    },
    // async readfile(item) {
    //   this.isFileLoading = true
    //   let ret = await this.$file.verifyfile(this.filepathStr + item.path)
    //   if (ret.code == -1) {
    //     this.$Notice({
    //       type: 'error',
    //       title: '错误',
    //       content: ret.msg
    //     });
    //     this.isFileLoading = false
    //     return
    //   }
    //   ret = await this.$file.readfile(this.filepathStr + item.path)
    //   this.editor = ret
    //   this.isFileLoading = false
    //   //this.randomkey = this.createRamdomKey()
    // },
    changePath(index) {
      //console.log(this.filepath.slice(0, index + 1))
      this.filepath = this.filepath.slice(0, index + 1)
      //   this.getFileList(this.filepathStr)
    },
    async getFileList(path) {
      this.isFileLoading = true
      this.filepath = path.split('/').filter((e) => { return e || e.trim() })
      let ret = await this.$file.list(path)
      if (ret.code < 0) {
        this.$Notice({
          type: 'error',
          title: '错误',
          content: ret.msg
        });
        this.isFileLoading = false
        return
      }
      this.fileData = ret.files
      this.isFileLoading = false
      //console.log(this.fileData)

    }
  }
}
</script>
<style lang="less" scoped>
.dropdown-item {
  padding: 10px;
  font-size: 12px;
  border-radius: 3px;
  // border:solid 1px rgba(47, 218, 178, 0.5);
  &:hover {
    background: rgba(47, 218, 178, 0.1);
  }
}
#file-breadcrumb {
  padding-right: 2px;
  display: flex;
  align-items: center;
  #file-breadcrumb-item {
    text-align: center;
    position: relative;
    cursor: pointer;
    // height: 20px;
    // min-width: 30px;
    margin: 0 1px;
    font-size: 14px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 3px;
    padding: 8px 10px;
    // font-weight: bold;
    color: rgb(45, 173, 143);
    flex-wrap: wrap;
    background: #caf5eb;
    &:hover {
      background: rgba(47, 218, 178, 0.4);
    }
    &:last-child {
      flex: 1;
      &:hover {
        background: #caf5eb;
      }
      cursor: default;
    }
  }
}
/deep/ .h-switchlist > span {
  padding: 10px;
}
.file-path {
  display: inline-block;
  padding: 10px;
  display: flex;
  align-items: center;
}
.file-panle {
  //   padding: 10px;
  //   margin-bottom: 20px;
  height: calc(100% - 60px);
  overflow: hidden;
  overflow-y: auto;
  //   border-top: solid 1px rgba(0, 0, 0, 0.08);
}
.file-list-box {
  .file-toolbar {
    height: 50px;
    padding: 7px 0;
    padding-bottom: 0;
    display: flex;
    align-items: center;
    .item {
      &:first-child {
        flex: 1;
      }
      display: flex;
      //   height: 100%;
      //   padding: 7px 0;
    }
  }
  height: calc(100% - 50px);
  /deep/ .h-table {
    height: 100%;
  }
  /deep/ .h-table-container {
    height: calc(100% - 50px);
    overflow: hidden;
    overflow-y: auto;
  }
  //   /deep/ tr {
  //     cursor: pointer;
  //   }
  /deep/ td div#file {
    cursor: pointer;
    display: flex;
    align-items: center;
    align-self: center;
    // padding: 0 10px;
    font-size: 1.1em;
    img {
      font-size: 1em;
    }
    i {
      font-size: 1.4em;
    }
  }
}
.file-icon-box {
  padding: 10px 0px;
  display: flex;
  // flex-direction: column;
  flex-wrap: wrap;
  #item {
    justify-content: center;
    align-items: center;
    border-radius: 6px;
    // border: solid 1px rgba(0, 0, 0, 0.08);
    height: 100px;
    width: 100px;
    margin: 5px;
    display: flex;
    // transition: 0.1s;
    // flex-direction: row;
    cursor: pointer;
    #size {
      font-size: 12px;
      color: #ccc;
    }
    .list-file,
    .list-dir {
      display: flex;
      justify-content: center;
      align-items: center;
      flex-direction: column;
      width: 100%;
      padding: 10px;
    }
    .list-dir {
      i {
        color: #2fdab2;
      }
    }
    &:hover {
      #size {
        color: #fff;
      }
      .list-dir {
        i {
          color: #fff;
        }
      }
      background: #2fdab2;
      box-shadow: 2px 2px 6px 3px rgba(47, 218, 178, 0.1);
      color: #fff;
    }
    i {
      font-size: 2em;
    }
    span {
      font-size: 14px;
      text-align: center;
      width: 80px;
      padding: 5px;
    }
  }
}
</style>
